package com.rao.config.websecurity.core;


import com.rao.entity.Role;
import com.rao.entity.User;
import com.rao.service.IUserRoleRelationService;
import com.rao.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * spring-security查询数据进行数据库匹配认证的关键地方
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    IUserService userService;
    @Resource
    IUserRoleRelationService userRoleRelationService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User sysUser = userService.queryByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("当前：【 " + username + " 】不存在");
        }
        /*拿到用户的role的id*/
        List<Role> roles = userRoleRelationService.queryByUserId(sysUser.getUserId());
        Set<String> permissions = roles.stream().map(Role::getName).collect(Collectors.toSet());
        SysUserDetails sysUserDetails = new SysUserDetails(username, sysUser.getPassword(), permissions);
        BeanUtils.copyProperties(sysUser, sysUserDetails);
        return sysUserDetails;
    }
}
